<template>
	<div v-if="countdown > 0" class="h-[24px] text-t-3 flex justify-center items-center">
		<span class="min-w-[25px] text-end">{{ countdown }}</span>
		s
	</div>
	<button
		v-else
		class="bg-transparent border-none base-code cursor-pointer"
		:class="[{ count: countdown }, disabled ? 'text-t-3' : 'text-primary']"
		@click="onClick">
		{{ countdown ? countdown + $t('action.resendCode') : $t('action.sendCode') }}
	</button>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useCountdown, useMessage } from '@/hooks'
import { checkAccount } from '@/api/account'
import { authorizedSendCode, getCountDown, sendCode } from '@/api/assistants'
import { t } from '@/utils'
import { AccountType, CodeType } from '@/enums'
import { useAppStore } from '@/store'

const props = defineProps({
	type: {
		type: Number,
		required: true
	},
	codeType: {
		type: Number,
		required: true
	},
	disabled: {
		type: Boolean,
		default: false
	},
	nameData: {
		type: String,
		default: ''
	},
	authorized: {
		type: Boolean,
		default: false
	}
})

const { countdown, reset } = useCountdown()
const store = useAppStore()
const message = useMessage()
const loading = ref(false)

const checkAccountSendCode = async () => {
	let pass = true
	try {
		const { data } = await checkAccount({
			type: props.type,
			nameData: props.nameData
		})
		pass = !data.exist
	} catch (e) {}
	return pass
}

const onClick = async () => {
	try {
		if (loading.value) {
			// if (countdown.value || props.disabled) {
			return
		}
		loading.value = true
		// loading = showLoading()
		// codeType = 2 / 4  如果验证手机号或者邮箱存在的话
		if (
			props.nameData &&
			(props.codeType === CodeType.bindding || props.codeType === CodeType.updateEmailOrMobile)
		) {
			const pass = await checkAccountSendCode()
			if (!pass) {
				const error =
					props.type === AccountType.mobile
						? 'appValidate.mobileValidate'
						: 'appValidate.emailValidate'
				message.error(t(error))
				// loading?.close()
				// loading = null
				loading.value = false
				return false
			}
		}

		const params = {
			type: props.type,
			codeType: props.codeType,
			nameData: props.nameData,
			language: store.lang
		}
		const api = props.authorized ? authorizedSendCode : sendCode
		await api(params)
		message.success(t('tip.sendCodeSuccess'))
		await getCountDownFn()
		loading.value = false
		// loading?.close()
		// loading = null
	} catch (error) {
		// loading?.close()
		// loading = null
		loading.value = false
		message.error(error)
	}
}

const getCountDownFn = async () => {
	try {
		const params = {
			type: props.type,
			codeType: props.codeType,
			path: props.authorized ? 'authorizedsendcode' : 'sendCode'
		}
		const { data } = await getCountDown(params)
		reset(data.countdown)
	} catch (error) {
		message.error(error)
	}
}

onMounted(() => getCountDownFn())
</script>
<style lang="scss" scoped></style>
